<script setup lang="ts">
import { LockOutlined, UserOutlined } from '@vicons/antd'
import { useUser } from '@/stores/modules/user';
import { forgetPassword, updatePasswordForget } from '@/api/Base/user';
import { showNotify } from 'vant';
const userStore = useUser()
definePage({
  name: 'login',
  meta: {
  },
})

const loginObj = reactive({
  account: "",
  pwd: "",
  showKeyboard: false,
  showPassword: false,
  loading: false
})

function _login() {
  if (!loginObj.account) {
    showNotify({ type: 'danger', message: '请输入账号' })
    return
  }
  if (!loginObj.pwd) {
    showNotify({ type: 'danger', message: '请输入密码' })
    return
  }

  loginObj.loading = true
  userStore.login({
    "account": loginObj.account,
    "password": loginObj.pwd
  })
  .catch(error => {
    showNotify({ type: 'danger', message: error.message || '登录失败' })
    // Keep the input values on login failure
    loginObj.account = loginObj.account
    loginObj.pwd = loginObj.pwd
  })
  .finally(() => {
    loginObj.loading = false
  })
}

const showForgetModal = ref(false);
const forgetFormRef = ref(null);
const verifyId = ref('');
const countdown = ref(0);
const forgetLoading = ref(false);
const forgetForm = reactive({
    idcard: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
});

async function sendVerifyCode() {
  if (!forgetForm.idcard) {
    showNotify({ type: 'danger', message: '请输入身份证号/邮箱/用户名' });
    return;
  }

  try {
    const { code, data } = await forgetPassword({ username: forgetForm.idcard });
    if (code === 0) { // Assuming 0 is SUCCESS code
      verifyId.value = data.verifyId;
      showNotify({ type: 'success', message: '验证码已发送' });
      startCountdown();
    } else {
      showNotify({ type: 'danger', message: '验证码发送失败' });
    }
  } catch (error) {
    showNotify({ type: 'danger', message: '验证码发送失败' });
  }
}

function startCountdown() {
  countdown.value = 60;
  const interval = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(interval);
    }
  }, 1000);
}

function handleBeforeClose(action) {
  if (action === 'confirm') {
    return forgetForm.newPassword === forgetForm.confirmPassword;
  }
  return true;
}

// 重置密码函数优化
async function handleResetPassword() {
  try {
    // 提交前先验证表单
    await forgetFormRef.value.validate()
    
    forgetLoading.value = true
    
    const { code } = await updatePasswordForget({
      newPassword: forgetForm.newPassword,
      verifyCode: forgetForm.code,
      username: forgetForm.idcard,
      verifyId: verifyId.value
    })

    if (code === 0) {
      showNotify({ type: 'success', message: '密码重置成功' })
      
      // 关闭模态框
      showForgetModal.value = false
      
      // 重置表单（使用表单方法）
      forgetFormRef.value.resetValidation()
      Object.assign(forgetForm, {
        idcard: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      })
      verifyId.value = ''
    } else {
      showNotify({ type: 'danger', message: '密码重置失败' })
    }
  } catch (error) {
    // 处理验证错误和API错误
    if(error instanceof Error) {
      showNotify({ type: 'danger', message: error.message || '密码重置失败' })
    }
  } finally {
    forgetLoading.value = false
  }
}
</script>

<template>

  <Container class="bg-[#e9ecf5] flex flex-col items-center">
    <h1 class="title-h1">拓维ERP手机端</h1>
    <h2 class="title-h2">简单·智能·高效·安全</h2>
    <div class="bg-transparent flex flex-col gap-24 mt-[70px]">
      <van-field class="input" input-align="center" :border="false" v-model="loginObj.account" placeholder="请输入账号">
        <template #left-icon>
          <UserOutlined class="w-20 h-20" />
        </template>
      </van-field>
      <van-field 
        class="input" 
        input-align="center" 
        v-model="loginObj.pwd" 
        :type="loginObj.showPassword ? 'text' : 'password'" 
        placeholder="请输入密码"
      >
        <template #left-icon>
          <LockOutlined class="w-20 h-20" />
        </template>
        <template #right-icon>
          <van-icon 
            :name="loginObj.showPassword ? 'eye-o' : 'closed-eye'" 
            @click="loginObj.showPassword = !loginObj.showPassword" 
          />
        </template>
      </van-field>
      <van-button 
        class="button button-text" 
        @click="_login"
        :loading="loginObj.loading"
        loading-text="登录中..."
      >
        登录
      </van-button>
      <a href="javascript:" @click="showForgetModal = true">忘记密码</a>
    </div>
  </Container>

  <!-- 忘记密码模态框 -->
  <van-dialog v-model:show="showForgetModal" title="忘记密码" show-cancel-button :before-close="handleBeforeClose">
    <van-form ref="forgetFormRef" @submit="handleResetPassword" class="p-4">
      <van-field v-model="forgetForm.idcard" name="idcard" label="账号" placeholder="请输入身份证号/手机号/邮箱"
        :rules="[{ required: true, message: '请输入账号信息' }]" />

      <van-field v-model="forgetForm.code" name="code" label="验证码" placeholder="请输入验证码"
        :rules="[{ required: true, message: '请输入验证码' }]">
        <template #button>
          <van-button size="small" :disabled="countdown > 0" @click.stop="sendVerifyCode">
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </van-button>
        </template>
      </van-field>

      <van-field v-model="forgetForm.newPassword" name="newPassword" label="新密码" type="password" placeholder="请输入新密码"
        :rules="[{ required: true, message: '请输入新密码' }]" />

      <van-field v-model="forgetForm.confirmPassword" name="confirmPassword" label="确认密码" type="password"
        placeholder="请再次输入新密码" :rules="[
          {
            required: true,
            message: '请确认新密码'
          },
          {
            validator: (val) => val === forgetForm.newPassword,
            message: '两次输入密码不一致'
          }
        ]" />

      <div class="mt-6 mb-4">
        <van-button block type="primary" native-type="submit" :loading="forgetLoading" loading-text="提交中...">
          确认重置
        </van-button>
      </div>
    </van-form>
  </van-dialog>
</template>
<style lang="less" scoped>
.title-h1 {
  width: 216px;
  height: 4rem;
  opacity: 1;
  font-family: Alimama ShuHeiTi;
  font-size: 36px;
  font-weight: bold;
  line-height: 4rem;
  letter-spacing: 0em;
  margin: 0px;
  background: linear-gradient(180deg, #235EFF 0%, #3F73FF 52%, #235EFF 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-fill-color: transparent;
}

.title-h2 {
  width: 154px;
  height: 14px;
  opacity: 1;

  font-family: 思源黑体;
  font-size: 14px;
  font-weight: normal;
  line-height: 14px;
  letter-spacing: 0em;

  /* 666 */
  color: #666666;
}

.input {
  width: 300px;
  height: 50px;
  border-radius: 25px;
  opacity: 1;

  background: #E3E8F7;

  backdrop-filter: blur(3px);
}

.input-text {
  opacity: 1;

  font-family: 思源黑体;
  font-size: 14px;
  font-weight: normal;
  line-height: 50px;
  letter-spacing: 0em;

  /* 333 */
  color: #333333;

}

.button {
  width: 300px;
  height: 50px;
  border-radius: 25px;
  opacity: 1;
  /* 主色 */
  background: #235EFF;
  backdrop-filter: blur(3px);
}

.button-text {
  opacity: 1;

  font-family: 思源黑体;
  font-size: 16px;
  font-weight: 500;
  line-height: 50px;
  text-align: center;
  letter-spacing: 0em;

  /* 纯白 */
  color: #FFFFFF;

}
</style>
